﻿using System;
using Deepcode.Flux.Core.Systems.CMS;
using Deepcode.Flux.Core.Systems.CMS.Mappings;
using System.Web;

public class URLHelper
{
	/// <summary>
	/// Gets the root content object based on domain name. If it can't find
	/// the root based on domain, attempts to search up the node tree from
	/// the known current node to a node of type Site.
	/// </summary>
	/// <returns></returns>
	public static ContentObject GetRoot()
	{
		// First, see if our page is within a known mapping path
		// for the domain we're using....IE: If localhost is mapped to /1/2/3
		// and our page is /1/2/3/4 we know the mapping holds a valid root.
		string DomainName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
		DomainMappings dm = new DomainMappings();
		DomainMapping m = dm.GetByDomain(DomainName);

		if (m != null)
		{
			ContentObject rootPage = m.Rootpage_Live;
			if (rootPage != null)
			{
				if (RequestCache.NodeObject == null) return rootPage;

				string rootPath = rootPage.NodePath + rootPage.NodeName;
				if (RequestCache.NodeObject.NodePath.StartsWith(rootPath))
					return rootPage;
			}
		}

		if (RequestCache.NodeObject == null) return null;
		
		// Search up the tree until we find a Site type
		ContentObject trav = RequestCache.NodeObject.ParentLive;
		while (trav != null)
		{
			if (trav.FK_STypeID == "channel") return trav;
			trav = trav.ParentLive;
		}

		return null;
	}

	/// <summary>
	/// Determines whether potentialChild is a child of parent
	/// </summary>
	/// <param name="parent">The parent.</param>
	/// <param name="potentialChild">The potential child.</param>
	public static bool IsAChildOf(ContentObject parent, ContentObject potentialChild)
	{
		if (parent.PK_ID == potentialChild.PK_ID) return true;
		string parentPath = String.Format("{0}{1}/", parent.NodePath, parent.NodeName);
		if (potentialChild.NodePath.StartsWith(parentPath)) return true;
		return false;
	}

	/// <summary>
	/// Get a ~/ address for the content object provided
	/// </summary>
	/// <param name="item"></param>
	/// <returns></returns>
	public static string GetURL(ContentObject item)
	{
		return String.Format("~/{0}/{1}.aspx", item.NodePath, item.NodeName);
	}

	/// <summary>
	/// Gets the resolved URL for the content object provided.
	/// </summary>
	/// <param name="item">The item.</param>
	/// <param name="page">The page.</param>
	/// <returns></returns>
	public static string GetResolvedURL(ContentObject item, System.Web.UI.Page page)
	{
		return page.ResolveUrl(GetURL(item));
	}
}
